package com.fks.fks_service.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class JwtTokenUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);

    /*jwt令牌的有效时间（毫秒）， 默认12小时*/
    private static long JWT_EXPIRATION = 12*60*60*1000;
    /*jwt令牌的刷新有效时间（毫秒）， 默认6小时*/
    private static long JWT_EXPIRATION_REFRESH = 12*60*60*1000;
    /*指定签名的时候使用的签名算法，jjwt已经将这部分内容封装好了*/
    private static final SignatureAlgorithm JWT_SIGN = SignatureAlgorithm.HS256;
    /*JWT密匙*/
    private static String JWT_SECRET = "AiRXWjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApkI7V5d9jITMiuA4ttwBLurSB9dwI6w50w4XqAfyaUvUrs2qPu3ACz5Ff16VOf3DXVVak+FbM5hkfyrbUac4Y82RYyDFKFuGb0ravZfiQCKganv6Nm6rj6uxT4duXT+IfAGxWKeUAsZxh0UUZ9R9ELNsxls13y+vr1HLeHPS8DEicfjALsN0B5wUOYw/aB2PIK18d32RYxZcuUC7/+Mo0HxCvo0FYikVI7uGcQ7GejXBLrHq7hHrt5zxGfLigA2yqIb51Yz3Xef3xrIS454TGiB3UVoBcLjO2RdBYLfzfA62sCHvk54vRgwHSzl57jolIDkMEa1cuORy5I9OI5FSGwIDAQAB";

    /**
     * 根据负责生成JWT的token
     */
    public static String createToken(Map<String, Object> claims) {
        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder()
                .setHeaderParam("typ","JWT")
                //自定义数据 Map<String, Object>
                .setClaims(claims)
                .setId(UUID.randomUUID().toString().replace("-",""))
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + JWT_EXPIRATION))
                .signWith(JWT_SIGN, JWT_SECRET);
        return builder.compact();
    }

    /**
     * 根据负责生成JWT的token
     */
    public static String createRefreshToken(Map<String, Object> claims) {
        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder()
                .setHeaderParam("typ","JWT")
                //自定义数据 Map<String, Object>
                .setClaims(claims)
                .setId(UUID.randomUUID().toString().replace("-",""))
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + JWT_EXPIRATION_REFRESH))
                .signWith(JWT_SIGN, JWT_SECRET);
        return builder.compact();
    }

    /**
     * 从token中获取JWT中的负载
     */
    public static Claims getClaims(String jwtToken) {
        Claims claims = Jwts.parser()
                .setSigningKey(JWT_SECRET)
                .parseClaimsJws(jwtToken)
                .getBody();
        return claims;
    }

    /**
     * 判断token是否已经过期
     */
    public static boolean isExpired(Claims claims) {
        Date expiredDate = claims.getExpiration();
        return expiredDate.before(new Date());
    }

    /**
     * 判断token是否已经过期
     */
    public static boolean isExpired(String jwtToken) {
        Claims claims = getClaims(jwtToken);
        Date expiredDate = claims.getExpiration();
        return expiredDate.before(new Date());
    }


    /**
     * 生成项目的jwt
     * @param userId
     * @return
     */
    public static String createJwtToken(String userId, String accountType) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("accountType", accountType);
        String jwtToken = JwtTokenUtil.createToken(claims);
        return jwtToken;
    }

    /**
     * 生成项目的jwt
     * @param userId
     * @return
     */
    public static String createJwtRefreshToken(String userId, String accountType) {
        Map<String, Object> refreshClaims = new HashMap<>();
        refreshClaims.put("userId", userId);
        refreshClaims.put("accountType", accountType);
        String jwtRefreshToken = JwtTokenUtil.createRefreshToken(refreshClaims);
        return jwtRefreshToken;
    }
}
